package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.PublishConstants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.PreOrderTypeEnum;
import com.ruoyi.common.enums.ShopStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.bo.*;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IPOrderService;
import com.ruoyi.system.service.IPStoreOrderService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单Service业务层处理
 *
 * @author ruoyi
 * @date 2022-08-01
 */
@RequiredArgsConstructor
@Service
public class PStoreOrderServiceImpl implements IPStoreOrderService {

    private final PStoreOrderMapper baseMapper;
    private final PStoreCartMapper cartMapper;
    private final PStoreProductMapper productMapper;
    private final PStoreProductAttrValueMapper attrValueMapper;
    private final PUserAddressMapper addressMapper;
    private final SysUserMapper userMapper;
    private final PStoreSeckillMapper seckillMapper;
    private final PStoreSeckillMangerMapper seckillMangerMapper;
    private final PStoreOrderInfoMapper orderInfoMapper;
    private final PAskCouponLogMapper couponLogMapper;
    private final PCategoryMapper categoryMapper;
    private final PAskCouponMapper askCouponMapper;
    private final POrderServiceImpl pOrderService;
    private final PUserBillMapper pUserBillMapper;
    private final IPOrderService ipOrderService;
    private final SysDictDataMapper sysDictDataMapper;

    /**
     * 查询订单
     */
    @Override
    public PStoreOrderVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询订单列表
     */
    @Override
    public TableDataInfo<PStoreOrderVo> queryPageList(PStoreOrderBo bo, PageQuery pageQuery) {
        QueryWrapper<PStoreOrder> lqw = Wrappers.query();
        lqw.eq(StringUtils.isNotBlank(bo.getOrderId()), "PStoreOrder::getOrderId", bo.getOrderId());
        lqw.eq(bo.getUid() != null, "PStoreOrder::getUid", bo.getUid());
        Page<PStoreOrderVo> result = baseMapper.selectVoLeftPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询订单列表
     */
    @Override
    public List<PStoreOrderVo> queryList(PStoreOrderBo bo) {
        LambdaQueryWrapper<PStoreOrder> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PStoreOrder> buildQueryWrapper(PStoreOrderBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PStoreOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getOrderId()), PStoreOrder::getOrderId, bo.getOrderId());
        lqw.eq(bo.getUid() != null, PStoreOrder::getUid, bo.getUid());
        lqw.like(StringUtils.isNotBlank(bo.getRealName()), PStoreOrder::getRealName, bo.getRealName());
        lqw.eq(StringUtils.isNotBlank(bo.getUserPhone()), PStoreOrder::getUserPhone, bo.getUserPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getUserAddress()), PStoreOrder::getUserAddress, bo.getUserAddress());
        return lqw;
    }

    /**
     * 新增订单
     */
    @Override
    public Boolean insertByBo(PStoreOrderBo bo) {
        PStoreOrder add = BeanUtil.toBean(bo, PStoreOrder.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改订单
     */
    @Override
    public Boolean updateByBo(PStoreOrderBo bo) {
        PStoreOrder update = BeanUtil.toBean(bo, PStoreOrder.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PStoreOrder entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除订单
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public TableDataInfo<StoreOrderDetailResponse> queryPageMyList(PStoreOrderBo bo, PageQuery pageQuery) {
        return null;
    }

    @Override
    public Map<String, Object> preOrder(PreOrderVo request) {
        if (StringUtils.isBlank(request.getPreOrderType())) {
            throw new ServiceException("预下单类型不能为空!");
        }

        if (CollUtil.isEmpty(request.getOrderDetails())) {
            throw new ServiceException("预下单订单详情列表不能为空");
        }
        // 校验预下单商品信息
        OrderInfoVo orderInfoVo = validatePreOrderRequest(request, LoginHelper.getUserId());
        // 商品总计金额
        BigDecimal totalPrice;
//        if (orderInfoVo.getOrderDetailList().get(0).getProductType().equals(PublishConstants.PRODUCT_TYPE_SHOP)) {
//            // 普通商品
//            totalPrice = orderInfoVo.getOrderDetailList().stream().map(e -> e.getVipPrice().multiply(new BigDecimal(e.getPayNum()))).reduce(BigDecimal.ZERO, BigDecimal::add);
//        } else {
//            totalPrice = orderInfoVo.getOrderDetailList().stream().map(e -> e.getPrice().multiply(new BigDecimal(e.getPayNum()))).reduce(BigDecimal.ZERO, BigDecimal::add);
//        }
        totalPrice = orderInfoVo.getOrderDetailList().stream().map(e -> e.getPrice().multiply(new BigDecimal(e.getPayNum()))).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderInfoVo.setProTotalFee(totalPrice);
        // 购买商品总数量
        int orderProNum = orderInfoVo.getOrderDetailList().stream().mapToInt(OrderInfoDetailVo::getPayNum).sum();
        orderInfoVo.setOrderProNum(orderProNum);
        // 获取默认地址
        Long userId = LoginHelper.getUserId();
        PUserAddress userAddress = addressMapper.selectOne(new LambdaQueryWrapper<PUserAddress>().eq(PUserAddress::getUid, userId).eq(PUserAddress::getIsDefault, PublishConstants.COMMON_YES));
        if (ObjectUtil.isNotNull(userAddress)) {
            // 计算运费
//            getFreightFee(orderInfoVo, userAddress);
            orderInfoVo.setAddressId(userAddress.getId());
            orderInfoVo.setRealName(userAddress.getRealName());
            orderInfoVo.setPhone(userAddress.getPhone());
            orderInfoVo.setProvince(userAddress.getProvince());
            orderInfoVo.setCity(userAddress.getCity());
            orderInfoVo.setDistrict(userAddress.getDistrict());
            orderInfoVo.setDetail(userAddress.getDetail());
        } else {
            orderInfoVo.setFreightFee(BigDecimal.ZERO);
        }
        // 填充单子金额信息
        SysUser user = userMapper.selectUserById(userId);
        if(orderInfoVo.getFreightFee() == null){
            orderInfoVo.setFreightFee(BigDecimal.ZERO);
        }
        orderInfoVo.setPayFee(orderInfoVo.getProTotalFee().add(orderInfoVo.getFreightFee()));
        orderInfoVo.setUserIntegral(user.getIntegral());
        orderInfoVo.setUserBalance(user.getBalance());
        // 缓存订单
        String key = user.getUserId() + DateUtils.getDate() + UUID.randomUUID().toString().replace("-", "");
        RedisUtils.setCacheObject(PublishConstants.ORDER_CACHE_PER + key, JSONUtil.toJsonStr(orderInfoVo), Duration.ofMinutes(PublishConstants.ORDER_CASH_CONFIRM));
        Map<String, Object> record = new HashMap<>();
        record.put("preOrderNo", key);
        return record;
    }

    @Override
    public PreOrderResponse loadPreOrder(String preOrderNo) {
        // 通过缓存获取预下单对象
        String key = PublishConstants.ORDER_CACHE_PER + preOrderNo;
        boolean exists = RedisUtils.hasKey(key);
        if (!exists) {
            throw new ServiceException("预下单订单不存在");
        }
        String orderVoString = RedisUtils.getCacheObject(key).toString();
        OrderInfoVo orderInfoVo = JsonUtils.parseObject(orderVoString, OrderInfoVo.class);
        PreOrderResponse preOrderResponse = new PreOrderResponse();
        preOrderResponse.setOrderInfoVo(orderInfoVo);
//        String payWeixinOpen = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_PAY_WEIXIN_OPEN);
//        if (orderInfoVo.getIsVideo()) {
//            // 关闭余额支付和到店自提
//            preOrderResponse.setYuePayStatus("0");
//            preOrderResponse.setPayWeixinOpen(payWeixinOpen);
//            preOrderResponse.setStoreSelfMention("false");
//            preOrderResponse.setAliPayStatus("0");
//            return preOrderResponse;
//        }
//        String yuePayStatus = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_YUE_PAY_STATUS);// 1开启 2关闭
//        String storeSelfMention = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_KEY_STORE_SELF_MENTION);
//        String aliPayStatus = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_ALI_PAY_STATUS);// 1开启
//        preOrderResponse.setYuePayStatus(yuePayStatus);
//        preOrderResponse.setPayWeixinOpen(payWeixinOpen);
//        preOrderResponse.setStoreSelfMention(storeSelfMention);
//        preOrderResponse.setAliPayStatus(aliPayStatus);
        return preOrderResponse;
    }

    @Override
    public Map<String, Object> createOrder(CreateOrderRequest request) {
        Long userId = LoginHelper.getUserId();
        // 通过缓存获取预下单对象
        String key = PublishConstants.ORDER_CACHE_PER + request.getPreOrderNo();
        boolean exists = RedisUtils.hasKey(key);
        if (!exists) {
            throw new ServiceException("预下单订单不存在");
        }
        String orderVoString = RedisUtils.getCacheObject(key).toString();
        OrderInfoVo orderInfoVo = JsonUtils.parseObject(orderVoString, OrderInfoVo.class);
        // 检测支付方式
//        if (!orderUtils.checkPayType(request.getPayType())) {
//            throw new ServiceException("暂不支持该支付方式，请刷新页面或者联系管理员");
//        }
//
//        if (request.getPayType().equals(PayConstants.PAY_TYPE_WE_CHAT)) {
//            // 检测支付渠道
//            if (StrUtil.isBlank(request.getPayChannel())) throw new ServiceException("支付渠道不能为空!");
//            if (!OrderUtils.checkPayChannel(request.getPayChannel())) throw new ServiceException("支付渠道不存在!");
//        }
        // 校验商品库存
        List<Map<String, Object>> skuRecordList = validateProductStock(orderInfoVo, userId);

        // 校验收货信息
        String verifyCode = "";
        String userAddressStr = "";
        if ("1".equals(request.getShippingType())) { // 快递配送
            if (request.getAddressId() <= 0) throw new ServiceException("请选择收货地址");
            PUserAddress userAddress = addressMapper.selectById(request.getAddressId());
            if (ObjectUtil.isNull(userAddress)) {
                throw new ServiceException("收货地址有误");
            }
            request.setRealName(userAddress.getRealName());
            request.setPhone(userAddress.getPhone());
            userAddressStr = userAddress.getProvince() + userAddress.getCity() + userAddress.getDistrict() + userAddress.getDetail();
        } else if ("2".equals(request.getShippingType())) { // 到店自提
            if (org.apache.commons.lang3.StringUtils.isBlank(request.getRealName()) || org.apache.commons.lang3.StringUtils.isBlank(request.getPhone())) {
                throw new ServiceException("请填写姓名和电话");
            }
            // 自提开关是否打开
//            String storeSelfMention = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_KEY_STORE_SELF_MENTION);
//            if (storeSelfMention.equals("false")) {
//                throw new ServiceException("请先联系管理员开启门店自提");
//            }
//            SystemStore systemStore = systemStoreService.getById(request.getStoreId());
//            if (ObjectUtil.isNull(systemStore) || systemStore.getIsDel() || !systemStore.getIsShow()) {
//                throw new ServiceException("暂无门店无法选择门店自提");
//            }
            verifyCode = CrmebUtil.randomCount(1111111111, 999999999) + "";
//            userAddressStr = systemStore.getName();
        }

        // 活动商品校验
        // 秒杀
        if (ObjectUtil.isNotNull(orderInfoVo.getSeckillId()) && orderInfoVo.getSeckillId() > 0) {
            PStoreSeckill storeSeckill = seckillMapper.selectById(orderInfoVo.getSeckillId());
            if (storeSeckill.getStatus().equals(0)) {
                throw new ServiceException("秒杀商品已关闭");
            }
            OrderInfoDetailVo detailVo = orderInfoVo.getOrderDetailList().get(0);
            PStoreProductAttrValue seckillAttrValue = getByIdAndProductIdAndType(detailVo.getAttrValueId(), orderInfoVo.getSeckillId(), PublishConstants.PRODUCT_TYPE_SECKILL);
            if (ObjectUtil.isNull(seckillAttrValue)) {
                throw new ServiceException("秒杀商品规格不存在");
            }
            commonValidateSeckill(storeSeckill, seckillAttrValue, userId, detailVo.getPayNum());
        }

        // 计算订单各种价格
        OrderComputedPriceRequest orderComputedPriceRequest = new OrderComputedPriceRequest();
        orderComputedPriceRequest.setShippingType(request.getShippingType());
        orderComputedPriceRequest.setAddressId(request.getAddressId());
        orderComputedPriceRequest.setCouponId(request.getCouponId());
        orderComputedPriceRequest.setUseIntegral(request.getUseIntegral());
        ComputedOrderPriceResponse computedOrderPriceResponse = computedPrice(orderComputedPriceRequest, orderInfoVo, userId);

        // 生成订单号
        String orderNo = CrmebUtil.getOrderNo("order");

        // 购买赠送的积分
        int gainIntegral = 0;
        List<PStoreOrderInfo> storeOrderInfos = new ArrayList<>();
        for (OrderInfoDetailVo detailVo : orderInfoVo.getOrderDetailList()) {
            // 赠送积分
            if (ObjectUtil.isNotNull(detailVo.getGiveIntegral()) && detailVo.getGiveIntegral() > 0) {
                gainIntegral += detailVo.getGiveIntegral() * detailVo.getPayNum();
            }
            // 订单详情
            PStoreOrderInfo soInfo = new PStoreOrderInfo();
            soInfo.setProductId(detailVo.getProductId());
            soInfo.setInfo(JsonUtils.toJsonString(detailVo));
            soInfo.setUnique(detailVo.getAttrValueId().toString());
            soInfo.setOrderNo(orderNo);
            soInfo.setProductName(detailVo.getProductName());
            soInfo.setAttrValueId(detailVo.getAttrValueId());
            soInfo.setImage(detailVo.getImage());
            soInfo.setSku(detailVo.getSku());
            soInfo.setPrice(detailVo.getPrice());
            soInfo.setPayNum(detailVo.getPayNum());
            soInfo.setWeight(detailVo.getWeight());
            soInfo.setVolume(detailVo.getVolume());
            if (ObjectUtil.isNotNull(detailVo.getGiveIntegral()) && detailVo.getGiveIntegral() > 0) {
                soInfo.setGiveIntegral(detailVo.getGiveIntegral());
            } else {
                soInfo.setGiveIntegral(0);
            }
            soInfo.setIsReply(PublishConstants.COMMON_NO);
            soInfo.setIsSub(detailVo.getIsSub());
            soInfo.setProductType(detailVo.getProductType());
            if (ObjectUtil.isNotNull(detailVo.getVipPrice())) {
                soInfo.setVipPrice(detailVo.getVipPrice());
            } else {
                soInfo.setVipPrice(detailVo.getPrice());
            }

            storeOrderInfos.add(soInfo);
        }

        // 下单赠送积分
//        if (computedOrderPriceResponse.getPayFee().compareTo(BigDecimal.ZERO) > 0) {
//            // 赠送积分比例
//            String integralStr = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_KEY_INTEGRAL_RATE_ORDER_GIVE);
//            if (StrUtil.isNotBlank(integralStr)) {
//                BigDecimal integralBig = new BigDecimal(integralStr);
//                int integral = integralBig.multiply(computedOrderPriceResponse.getPayFee()).setScale(0, BigDecimal.ROUND_DOWN).intValue();
//                if (integral > 0) {
//                    // 添加积分
//                    gainIntegral += integral;
//                }
//            }
//        }

        PStoreOrder storeOrder = new PStoreOrder();
        storeOrder.setUid(userId);
        storeOrder.setOrderId(orderNo);
        storeOrder.setRealName(request.getRealName());
        storeOrder.setUserPhone(request.getPhone());
        storeOrder.setUserAddress(userAddressStr);
        // 如果是自提
        if ("2".equals(request.getShippingType())) {
            storeOrder.setVerifyCode(verifyCode);
            storeOrder.setStoreId(request.getStoreId());
        }
        storeOrder.setTotalNum(orderInfoVo.getOrderProNum());
        storeOrder.setCouponId(request.getCouponId());
        // 订单总价
        BigDecimal totalPrice = computedOrderPriceResponse.getProTotalFee().add(computedOrderPriceResponse.getFreightFee());

        storeOrder.setTotalPrice(totalPrice);
        storeOrder.setProTotalPrice(computedOrderPriceResponse.getProTotalFee());
        storeOrder.setTotalPostage(computedOrderPriceResponse.getFreightFee());
        storeOrder.setCouponPrice(computedOrderPriceResponse.getCouponFee());
        storeOrder.setPayPrice(computedOrderPriceResponse.getPayFee());
        storeOrder.setPayPostage(computedOrderPriceResponse.getFreightFee());
        storeOrder.setDeductionPrice(computedOrderPriceResponse.getDeductionPrice());
        storeOrder.setPayType(request.getPayType());
        storeOrder.setUseIntegral(computedOrderPriceResponse.getUsedIntegral());
        storeOrder.setGainIntegral(gainIntegral);
        storeOrder.setMark(StringEscapeUtils.escapeHtml4(request.getMark()));
        storeOrder.setCombinationId(orderInfoVo.getCombinationId());
        storeOrder.setPinkId(orderInfoVo.getPinkId());
        storeOrder.setSeckillId(orderInfoVo.getSeckillId());
        storeOrder.setBargainId(orderInfoVo.getBargainId());
        storeOrder.setBargainUserId(orderInfoVo.getBargainUserId());
        storeOrder.setCreateTime(DateUtil.nowDateTime());
        storeOrder.setShippingType(request.getShippingType());
//        storeOrder.setIsChannel(isChannel);
        storeOrder.setPaid(PublishConstants.COMMON_NO);
        storeOrder.setCost(BigDecimal.ZERO);
        storeOrder.setType("0");
        PAskCouponLog storeCouponUser = new PAskCouponLog();
        // 优惠券修改
        if (storeOrder.getCouponId() > 0) {
            storeCouponUser = couponLogMapper.selectById(storeOrder.getCouponId());
            storeCouponUser.setStatus(1);
        }
        PAskCouponLog finalStoreCouponUser = storeCouponUser;
        // 扣减库存
        // 需要根据是否活动商品，扣减不同的库存
        // 秒杀扣库存
        if (storeOrder.getSeckillId() > 0) {
            Map<String, Object> skuRecord = skuRecordList.get(0);
            // 秒杀商品扣库存
            operationSeckillStock(getLong(skuRecord.get("activityId")), getInt(skuRecord.get("num")), "sub");
            // 秒杀商品规格扣库存
            operationProductAttrValueStock(getLong(skuRecord.get("activityAttrValueId")), getInt(skuRecord.get("num")), "sub", Integer.parseInt(PublishConstants.PRODUCT_TYPE_SECKILL));
            // 普通商品口库存
            operationProductStock(getLong(skuRecord.get("productId")), getInt(skuRecord.get("num")), "sub");
            // 普通商品规格扣库存
            operationProductAttrValueStock(getLong(skuRecord.get("attrValueId")), getInt(skuRecord.get("num")), "sub", Integer.parseInt(PublishConstants.PRODUCT_TYPE_SHOP));
        } else {
            // 普通商品
            for (Map<String, Object> skuRecord : skuRecordList) {
                // 普通商品口库存
                operationProductStock(getLong(skuRecord.get("productId")), getInt(skuRecord.get("num")), "sub");
                // 普通商品规格扣库存
                operationProductAttrValueStock(getLong(skuRecord.get("attrValueId")), getInt(skuRecord.get("num")), "sub", Integer.parseInt(PublishConstants.PRODUCT_TYPE_SHOP));
            }
        }

        baseMapper.insert(storeOrder);
        storeOrderInfos.forEach(info -> info.setOrderId(storeOrder.getId()));
        // 优惠券修改
        if (storeOrder.getCouponId() > 0) {
            couponLogMapper.updateById(finalStoreCouponUser);
        }
        // 保存购物车商品详情
        orderInfoMapper.insertBatch(storeOrderInfos);
        // 清除购物车数据
        if (CollUtil.isNotEmpty(orderInfoVo.getCartIdList())) {
            cartMapper.deleteBatchIds(orderInfoVo.getCartIdList());
        }

        // 删除缓存订单
        if (RedisUtils.hasKey(key)) {
            RedisUtils.deleteObject(key);
        }
        // 加入自动未支付自动取消队列
        // RedisUtils.publish(PublishConstants.ORDER_AUTO_CANCEL_KEY, storeOrder.getOrderId());

        Map<String, Object> record = new HashMap<>();
        record.put("orderNo", storeOrder.getOrderId());
        return record;
    }

    @Override
    public TableDataInfo<OrderDetailResponse> queryPageMyFontList(PStoreOrderBo bo, PageQuery pageQuery) {
        long userId = LoginHelper.getUserId();
        LambdaQueryWrapper<PStoreOrder> lqw = new LambdaQueryWrapper<PStoreOrder>()
            .eq(PStoreOrder::getUid, userId)
            .eq(PStoreOrder::getStatus, bo.getStatus());
        Page<PStoreOrder> orderList = baseMapper.selectVoMyFontPage(pageQuery.build(), lqw);
        if (CollUtil.isNotEmpty(orderList.getRecords())) {
            List<OrderDetailResponse> responseList = CollUtil.newArrayList();
            for (PStoreOrder storeOrder : orderList.getRecords()) {
                OrderDetailResponse infoResponse = new OrderDetailResponse();
                BeanUtils.copyProperties(storeOrder, infoResponse);
                // 订单状态
//            infoResponse.setOrderStatus(getH5OrderStatus(storeOrder));
//            // 活动类型
//            infoResponse.setActivityType(getOrderActivityType(storeOrder));
                // 订单详情对象列表
                List<PStoreOrderInfo> orderInfoList = orderInfoMapper.selectList(
                    new LambdaQueryWrapper<PStoreOrderInfo>().eq(PStoreOrderInfo::getOrderNo, storeOrder.getOrderId())
                );
                List<OrderInfoResponse> infoResponseList = CollUtil.newArrayList();
                orderInfoList.forEach(e -> {
                    OrderInfoResponse orderInfoResponse = new OrderInfoResponse();
                    orderInfoResponse.setStoreName(e.getProductName());
                    orderInfoResponse.setImage(e.getImage());
                    orderInfoResponse.setCartNum(e.getPayNum());
                    orderInfoResponse.setPrice(ObjectUtil.isNotNull(e.getVipPrice()) ? e.getVipPrice() : e.getPrice());
                    orderInfoResponse.setProductId(e.getProductId());
                    infoResponseList.add(orderInfoResponse);
                });
                infoResponse.setOrderInfoList(infoResponseList);
                responseList.add(infoResponse);
            }

            return TableDataInfo.build(responseList);
        }

        return new TableDataInfo<>();
    }

    @Override
    public StoreOrderDetailInfoResponse detailOrder(Long id) {
        Long userId = LoginHelper.getUserId();

        StoreOrderDetailInfoResponse storeOrderDetailResponse = new StoreOrderDetailInfoResponse();
        // 查询订单
        PStoreOrder storeOrder = baseMapper.selectById(id);
        if (ObjectUtil.isNull(storeOrder)) {
            throw new ServiceException("订单不存在");
        }
        if (!storeOrder.getUid().equals(userId)) {
            throw new ServiceException("订单不存在");
        }

        BeanUtils.copyProperties(storeOrder, storeOrderDetailResponse);
        // 订单详情对象列表
        List<OrderInfoResponse> infoResponseList = CollUtil.newArrayList();
        List<PStoreOrderInfo> infoList = orderInfoMapper.selectList(new LambdaQueryWrapper<PStoreOrderInfo>().eq(PStoreOrderInfo::getOrderNo, storeOrder.getOrderId()));
        infoList.forEach(e -> {
            OrderInfoResponse orderInfoResponse = new OrderInfoResponse();
            orderInfoResponse.setStoreName(e.getProductName());
            orderInfoResponse.setImage(e.getImage());
            orderInfoResponse.setCartNum(e.getPayNum());
            orderInfoResponse.setPrice(ObjectUtil.isNotNull(e.getVipPrice()) ? e.getVipPrice() : e.getPrice());
            orderInfoResponse.setProductId(e.getProductId());
            orderInfoResponse.setIsReply(e.getIsReply());
            orderInfoResponse.setAttrId(e.getAttrValueId());
            orderInfoResponse.setSku(e.getSku());
            infoResponseList.add(orderInfoResponse);
        });
        storeOrderDetailResponse.setOrderInfoList(infoResponseList);

        // 系统门店信息
//        SystemStore systemStorePram = new SystemStore();
//        systemStorePram.setId(storeOrder.getStoreId());
//        storeOrderDetailResponse.setSystemStore(systemStoreService.getByCondition(systemStorePram));
        // 腾讯云地图key
//        storeOrderDetailResponse.setMapKey(systemConfigService.getValueByKey(SysConfigConstants.CONFIG_SITE_TENG_XUN_MAP_KEY));
//        BeanUtils.copyProperties(storeOrder, storeOrderDetailResponse);
//        storeOrderDetailResponse.setStatusPic(orderStatusVo.getStr("statusPic"));
//        storeOrderDetailResponse.setOrderStatusMsg(orderStatusVo.getStr("msg"));
//        storeOrderDetailResponse.setPayTypeStr(orderStatusVo.getStr("payTypeStr"));
        BigDecimal proTotalPrice = storeOrderDetailResponse.getPayPrice().add(storeOrderDetailResponse.getCouponPrice()).add(storeOrderDetailResponse.getDeductionPrice()).subtract(storeOrderDetailResponse.getPayPostage());
        storeOrderDetailResponse.setProTotalPrice(proTotalPrice);
        return storeOrderDetailResponse;
    }

    @Override
    public void cancelOrder(PStoreOrderBo bo) {
        String orderId = bo.getOrderId();
        if (StringUtils.isBlank(orderId)) {
            throw new ServiceException("订单编号不能为空!");
        }

        baseMapper.update(null, new LambdaUpdateWrapper<PStoreOrder>().set(PStoreOrder::getStatus, ShopStatus.CANCELLED.getValue()).eq(PStoreOrder::getOrderId, orderId));
    }

    @Override
    public void takeOrder(PStoreOrderBo bo) {
        String orderId = bo.getOrderId();
        if (StringUtils.isBlank(orderId)) {
            throw new ServiceException("订单编号不能为空!");
        }

        baseMapper.update(null, new LambdaUpdateWrapper<PStoreOrder>().set(PStoreOrder::getStatus, ShopStatus.GETTING.getValue()).eq(PStoreOrder::getOrderId, orderId));
        // 订单支付金额
        BigDecimal payPrice = bo.getPayPrice();
/*        SysDictData data = this.sysDictDataMapper.selectOne(new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getDictType, "sys_scale").eq(SysDictData::getDictLabel, "扣除比例"));

        // 按照比例扣除平台费
        BigDecimal deduct = new BigDecimal(data.getDictValue());
        //商户
        SysUser mer = this.userMapper.selectUserFontById(bo.getMerId().longValue());
        mer.setBalance(mer.getBalance().add(payPrice.multiply(deduct.multiply(new BigDecimal("100")))));
        this.userMapper.updateById(mer);*/

        // 消费订单结束获取金额增加会员等级
        this.ipOrderService.upgrade(bo.getUid(), payPrice);

    }

    private long getLong(Object column) {
        return (long) column;
    }

    private int getInt(Object column) {
        return (int) column;
    }

    /**
     * 添加(退货)/扣减库存
     *
     * @param id   秒杀商品id
     * @param num  数量
     * @param type 类型：add—添加，sub—扣减
     * @return Boolean
     */
    public Boolean operationSeckillStock(long id, Integer num, String type) {
        UpdateWrapper<PStoreSeckill> updateWrapper = new UpdateWrapper<>();
        if (type.equals("add")) {
            updateWrapper.setSql(StrUtil.format("stock = stock + {}", num));
            updateWrapper.setSql(StrUtil.format("sales = sales - {}", num));
            updateWrapper.setSql(StrUtil.format("quota = quota + {}", num));
        }
        if (type.equals("sub")) {
            updateWrapper.setSql(StrUtil.format("stock = stock - {}", num));
            updateWrapper.setSql(StrUtil.format("sales = sales + {}", num));
            updateWrapper.setSql(StrUtil.format("quota = quota - {}", num));
            // 扣减时加乐观锁保证库存不为负
            updateWrapper.last(StrUtil.format(" and (quota - {} >= 0)", num));
        }
        updateWrapper.eq("id", id);
        int update = seckillMapper.update(new PStoreSeckill().setId(id), updateWrapper);
        if (update < 1) {
            throw new ServiceException("更新商品库存失败！商品id = " + id);
        }
        return true;
    }

    /**
     * 添加(退货)/扣减库存
     *
     * @param id            秒杀商品id
     * @param num           数量
     * @param operationType 类型：add—添加，sub—扣减
     * @param type          活动类型 0=商品，1=秒杀，2=砍价，3=拼团
     * @return Boolean
     */
    public void operationProductAttrValueStock(Long id, Integer num, String operationType, Integer type) {
        UpdateWrapper<PStoreProductAttrValue> updateWrapper = new UpdateWrapper<>();
        if (operationType.equals("add")) {
            updateWrapper.setSql(StrUtil.format("stock = stock + {}", num));
            updateWrapper.setSql(StrUtil.format("sales = sales - {}", num));
            if (type > 0) {
                updateWrapper.setSql(StrUtil.format("quota = quota + {}", num));
            }
        }
        if (operationType.equals("sub")) {
            updateWrapper.setSql(StrUtil.format("stock = stock - {}", num));
            updateWrapper.setSql(StrUtil.format("sales = sales + {}", num));
            if (type > 0) {
                updateWrapper.setSql(StrUtil.format("quota = quota - {}", num));
                // 扣减时加乐观锁保证库存不为负
                updateWrapper.last(StrUtil.format("and (quota - {} >= 0)", num));
            } else {
                // 扣减时加乐观锁保证库存不为负
                updateWrapper.last(StrUtil.format("and (stock - {} >= 0)", num));
            }
        }
        updateWrapper.eq("id", id);
        updateWrapper.eq("type", type);
        attrValueMapper.update(null, updateWrapper);
    }

    /**
     * 添加/扣减库存
     *
     * @param id   商品id
     * @param num  数量
     * @param type 类型：add—添加，sub—扣减
     */
    public void operationProductStock(long id, Integer num, String type) {
        UpdateWrapper<PStoreProduct> updateWrapper = new UpdateWrapper<>();
        if (type.equals("add")) {
            updateWrapper.setSql(StrUtil.format("stock = stock + {}", num));
            updateWrapper.setSql(StrUtil.format("sales = sales - {}", num));
        }
        if (type.equals("sub")) {
            updateWrapper.setSql(StrUtil.format("stock = stock - {}", num));
            updateWrapper.setSql(StrUtil.format("sales = sales + {}", num));
            // 扣减时加乐观锁保证库存不为负
            updateWrapper.last(StrUtil.format(" and (stock - {} >= 0)", num));
        }
        updateWrapper.eq("id", id);
        productMapper.update(null, updateWrapper);
    }

    private ComputedOrderPriceResponse computedPrice(OrderComputedPriceRequest request, OrderInfoVo orderInfoVo, long userId) {
        SysUser user = userMapper.selectById(userId);
        // 计算各种价格
        ComputedOrderPriceResponse priceResponse = new ComputedOrderPriceResponse();
        // 计算运费
        if (request.getShippingType().equals("2")) {// 到店自提，不计算运费
            priceResponse.setFreightFee(BigDecimal.ZERO);
        } else if (ObjectUtil.isNull(request.getAddressId()) || request.getAddressId() <= 0) {
            // 快递配送，无地址
            priceResponse.setFreightFee(BigDecimal.ZERO);
        } else {// 快递配送，有地址
            PUserAddress userAddress = addressMapper.selectById(request.getAddressId());
            if (ObjectUtil.isNull(userAddress)) {
                priceResponse.setFreightFee(BigDecimal.ZERO);
            } else {
//                getFreightFee(orderInfoVo, userAddress);
                priceResponse.setFreightFee(orderInfoVo.getFreightFee());
            }
        }
        // 计算优惠券金额
        if (ObjectUtil.isNull(request.getCouponId()) || request.getCouponId() <= 0) {
            priceResponse.setCouponFee(BigDecimal.ZERO);
        } else if (orderInfoVo.getSeckillId() > 0 || orderInfoVo.getBargainId() > 0 || orderInfoVo.getCombinationId() > 0) {
            throw new ServiceException("营销活动商品无法使用优惠券");
        } else if (orderInfoVo.getIsVideo()) {
            throw new ServiceException("视频号商品无法使用优惠券");
        } else {
            // 判断优惠券是否可以使用
            PAskCouponLog storeCouponUser = couponLogMapper.selectById(request.getCouponId());
            if (ObjectUtil.isNull(storeCouponUser) || !storeCouponUser.getUid().equals(userId)) {
                throw new ServiceException("优惠券领取记录不存在！");
            }
            if (storeCouponUser.getStatus() == 1) {
                throw new ServiceException("此优惠券已使用！");
            }

            if (storeCouponUser.getStatus() == 2) {
                throw new ServiceException("此优惠券已失效！");
            }
            //判断是否在使用时间内
            Date date = DateUtil.nowDateTime();
            if (storeCouponUser.getStartTime().compareTo(date) > 0) {
                throw new ServiceException("此优惠券还未到达使用时间范围之内！");
            }
            if (date.compareTo(storeCouponUser.getEndTime()) > 0) {
                throw new ServiceException("此优惠券已经失效了");
            }
            if (storeCouponUser.getMinPrice().compareTo(orderInfoVo.getProTotalFee()) > 0) {
                throw new ServiceException("总金额小于优惠券最小使用金额");
            }
            //检测优惠券信息
            if (Integer.parseInt(storeCouponUser.getUseType()) > 1) {
                List<Long> productIdList = orderInfoVo.getOrderDetailList().stream().map(OrderInfoDetailVo::getProductId).collect(Collectors.toList());
                if (productIdList.size() < 1) {
                    throw new ServiceException("没有找到商品");
                }

                //设置优惠券所提供的集合
                List<Long> primaryKeyIdList = CrmebUtil.stringToLongArray(storeCouponUser.getPrimaryKey());

                //取两个集合的交集，如果是false则证明没有相同的值
                //oldList.retainAll(newList)返回值代表oldList是否保持原样，如果old和new完全相同，那old保持原样并返回false。
                //交集：listA.retainAll(listB) ——listA内容变为listA和listB都存在的对象；listB不变
                if (Integer.parseInt(storeCouponUser.getUseType()) == 2) {
                    primaryKeyIdList.retainAll(productIdList);
                    if (CollUtil.isEmpty(primaryKeyIdList)) {
                        throw new ServiceException("此优惠券为商品券，请购买相关商品之后再使用！");
                    }
                }

                if (Integer.parseInt(storeCouponUser.getUseType()) == 3) {
                    //拿出需要使用优惠券的商品分类集合
                    List<Integer> categoryIdList = getSecondaryCategoryByProductId(org.apache.commons.lang3.StringUtils.join(productIdList, ","));

                    primaryKeyIdList.retainAll(categoryIdList);
                    if (CollUtil.isEmpty(primaryKeyIdList)) {
                        throw new ServiceException("此优惠券为分类券，请购买相关分类下的商品之后再使用！");
                    }
                }
            }

            if (orderInfoVo.getProTotalFee().compareTo(storeCouponUser.getMoney()) <= 0) {
                priceResponse.setCouponFee(orderInfoVo.getProTotalFee());
                priceResponse.setDeductionPrice(BigDecimal.ZERO);
                priceResponse.setSurplusIntegral(user.getIntegral());
                priceResponse.setPayFee(priceResponse.getFreightFee());
                priceResponse.setUsedIntegral(0);
                priceResponse.setUseIntegral("0");
                priceResponse.setProTotalFee(orderInfoVo.getProTotalFee());
                return priceResponse;
            } else {
                priceResponse.setCouponFee(storeCouponUser.getMoney());
            }
        }
        // 积分部分
        BigDecimal payPrice = orderInfoVo.getProTotalFee().add(priceResponse.getFreightFee()).subtract(priceResponse.getCouponFee());
        priceResponse.setUseIntegral(request.getUseIntegral());
        priceResponse.setProTotalFee(orderInfoVo.getProTotalFee());
        if (PublishConstants.COMMON_NO.equals(request.getUseIntegral()) || user.getIntegral() <= 0) {// 不使用积分
            priceResponse.setDeductionPrice(BigDecimal.ZERO);
            priceResponse.setSurplusIntegral(user.getIntegral());
            priceResponse.setPayFee(payPrice);
            priceResponse.setUsedIntegral(0);
            return priceResponse;
        }
        // 使用积分
        // 查询积分使用比例
//        String integralRatio = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_KEY_INTEGRAL_RATE);
//        BigDecimal deductionPrice = new BigDecimal(user.getIntegral()).multiply(new BigDecimal(integralRatio));
//        if (PublishConstants.COMMON_YES.equals(request.getUseIntegral())) {
//            // 积分兑换金额小于实际支付金额
//            if (deductionPrice.compareTo(payPrice) < 0) {
//                payPrice = payPrice.subtract(deductionPrice);
//                priceResponse.setSurplusIntegral(0);
//                priceResponse.setUsedIntegral(user.getIntegral());
//            } else {
//                deductionPrice = payPrice;
//                if (payPrice.compareTo(BigDecimal.ZERO) > 0) {
//                    int usedIntegral = payPrice.divide(new BigDecimal(integralRatio), 0, BigDecimal.ROUND_UP).intValue();
//                    priceResponse.setSurplusIntegral(user.getIntegral() - usedIntegral);
//                    priceResponse.setUsedIntegral(usedIntegral);
//                }
//                payPrice = BigDecimal.ZERO;
//            }
//            priceResponse.setPayFee(payPrice);
//            priceResponse.setDeductionPrice(deductionPrice);
//        }
        return priceResponse;
    }

    /**
     * 根据商品id取出二级分类
     *
     * @param productIdStr String 商品分类
     * @return List<Integer>
     */
    public List<Integer> getSecondaryCategoryByProductId(String productIdStr) {
        List<Integer> idList = new ArrayList<>();

        if (org.apache.commons.lang3.StringUtils.isBlank(productIdStr)) {
            return idList;
        }
        List<Integer> productIdList = CrmebUtil.stringToArray(productIdStr);
        LambdaQueryWrapper<PStoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(PStoreProduct::getId, productIdList);
        List<PStoreProduct> productList = productMapper.selectList(lambdaQueryWrapper);
        if (productIdList.size() < 1) {
            return idList;
        }

        //把所有的分类id写入集合
        for (PStoreProduct storeProduct : productList) {
            List<Integer> categoryIdList = CrmebUtil.stringToArray(storeProduct.getCateId());
            idList.addAll(categoryIdList);
        }

        //去重
        List<Integer> cateIdList = idList.stream().distinct().collect(Collectors.toList());
        if (cateIdList.size() < 1) {
            return idList;
        }

        //取出所有的二级分类
        List<PCategory> categoryList = categoryMapper.selectBatchIds(cateIdList);
        if (categoryList.size() < 1) {
            return idList;
        }

        for (PCategory category : categoryList) {
            List<Integer> parentIdList = CrmebUtil.stringToArrayByRegex(category.getPath(), "/");
            if (parentIdList.size() > 2) {
                Integer secondaryCategoryId = parentIdList.get(2);
                if (secondaryCategoryId > 0) {
                    idList.add(secondaryCategoryId);
                }
            }
        }
        return idList;
    }

    /**
     * 校验商品库存（生成订单）
     *
     * @param orderInfoVo 订单详情Vo
     * @return List<MyRecord>
     * skuRecord 扣减库存对象
     * ——activityId             活动商品id
     * ——activityAttrValueId    活动商品skuId
     * ——productId              普通（主）商品id
     * ——attrValueId            普通（主）商品skuId
     * ——num                    购买数量
     */
    private List<Map<String, Object>> validateProductStock(OrderInfoVo orderInfoVo, long userId) {
        List<Map<String, Object>> recordList = CollUtil.newArrayList();
        if (orderInfoVo.getSeckillId() > 0) {
            // 秒杀部分判断
            long seckillId = orderInfoVo.getSeckillId();
            OrderInfoDetailVo detailVo = orderInfoVo.getOrderDetailList().get(0);
            PStoreSeckill storeSeckill = seckillMapper.selectById(seckillId);
            PStoreProductAttrValue seckillAttrValue = getByIdAndProductIdAndType(detailVo.getAttrValueId(), seckillId, PublishConstants.PRODUCT_TYPE_SECKILL);
            if (ObjectUtil.isNull(seckillAttrValue)) {
                throw new ServiceException("秒杀商品规格不存在");
            }
            Map<String, Object> seckillRecord = commonValidateSeckill(storeSeckill, seckillAttrValue, userId, detailVo.getPayNum());
            // 主商品sku
            PStoreProductAttrValue productAttrValue = (PStoreProductAttrValue) seckillRecord.get("productAttrValue");

            Map<String, Object> record = new HashMap<>();
            record.put("activityId", seckillId);
            record.put("activityAttrValueId", seckillAttrValue.getId());
            record.put("productId", storeSeckill.getProductId());
            record.put("attrValueId", productAttrValue.getId());
            record.put("num", detailVo.getPayNum());
            recordList.add(record);
            return recordList;
        }
        // 普通商品
        List<OrderInfoDetailVo> orderDetailList = orderInfoVo.getOrderDetailList();
        orderDetailList.forEach(e -> {
            // 查询商品信息
            PStoreProduct storeProduct = productMapper.selectById(e.getProductId());
            if (ObjectUtil.isNull(storeProduct)) {
                throw new ServiceException("购买的商品信息不存在");
            }

            if ("0".equals(storeProduct.getIsShow())) {
                throw new ServiceException("购买的商品已下架");
            }

            if (storeProduct.getStock().equals(0) || e.getPayNum() > storeProduct.getStock()) {
                throw new ServiceException("购买的商品库存不足");
            }
            // 查询商品规格属性值信息
            PStoreProductAttrValue attrValue = getByIdAndProductIdAndType(e.getAttrValueId(), e.getProductId(), PublishConstants.PRODUCT_TYPE_SHOP);
            if (ObjectUtil.isNull(attrValue)) {
                throw new ServiceException("购买的商品规格信息不存在");
            }

            if (attrValue.getStock() < e.getPayNum()) {
                throw new ServiceException("购买的商品库存不足");
            }

            Map<String, Object> record = new HashMap<>();
            record.put("productId", e.getProductId());
            record.put("num", e.getPayNum());
            record.put("attrValueId", e.getAttrValueId());
            recordList.add(record);
        });

        return recordList;
    }

    /**
     * 校验预下单商品信息
     */
    private OrderInfoVo validatePreOrderRequest(PreOrderVo request, long userId) {
        OrderInfoVo orderInfoVo = new OrderInfoVo();
        // 订单详情数组
        List<OrderInfoDetailVo> detailVoList = CollUtil.newArrayList();
        // 购物车购买
        if (PreOrderTypeEnum.SHOPPING_CART.getValue().equals(request.getPreOrderType())) {
            detailVoList = validatePreOrderShopping(request, userId);
            List<Long> cartIdList = request.getOrderDetails().stream().map(PreOrderDetailVo::getShoppingCartId).distinct().collect(Collectors.toList());
            orderInfoVo.setCartIdList(cartIdList);
        }
        // 立即购买
        if (PreOrderTypeEnum.BUY_NOW.getValue().equals(request.getPreOrderType())) {
            // 立即购买只会有一条详情
            PreOrderDetailVo detailRequest = request.getOrderDetails().get(0);
            // 秒杀
            if (ObjectUtil.isNotEmpty(detailRequest.getSeckillId())) {
                detailVoList.add(validatePreOrderSeckill(detailRequest, userId));
                orderInfoVo.setSeckillId(detailRequest.getSeckillId());
            } else if (ObjectUtil.isNotEmpty(detailRequest.getBargainId())) {
                // 砍价
                detailVoList.add(validatePreOrderBargain(detailRequest, userId));
                orderInfoVo.setBargainId(detailRequest.getBargainId());
                orderInfoVo.setBargainUserId(detailRequest.getBargainUserId());
            } else if (ObjectUtil.isNotEmpty(detailRequest.getCombinationId())) {
                // 拼团
                detailVoList.add(validatePreOrderCombination(detailRequest, userId));
                orderInfoVo.setCombinationId(detailRequest.getCombinationId());
                orderInfoVo.setPinkId(detailRequest.getPinkId());
            } else {
                // 普通商品
                if (ObjectUtil.isNull(detailRequest.getProductId())) {
                    throw new ServiceException("商品编号不能为空");
                }
                if (ObjectUtil.isNull(detailRequest.getAttrValueId())) {
                    throw new ServiceException("商品规格属性值不能为空");
                }
                if (ObjectUtil.isNull(detailRequest.getProductNum()) || detailRequest.getProductNum() < 0) {
                    throw new ServiceException("购买数量必须大于0");
                }
                // 查询商品信息
                PStoreProduct storeProduct = productMapper.selectById(detailRequest.getProductId());
                if (ObjectUtil.isNull(storeProduct)) {
                    throw new ServiceException("商品信息不存在，请刷新后重新选择");
                }
                if (PublishConstants.COMMON_NO.equals(storeProduct.getIsShow())) {
                    throw new ServiceException("商品已下架，请刷新后重新选择");
                }
                if (storeProduct.getStock() < detailRequest.getProductNum()) {
                    throw new ServiceException("商品库存不足，请刷新后重新选择");
                }
                // 查询商品规格属性值信息
                PStoreProductAttrValue attrValue = getByIdAndProductIdAndType(detailRequest.getAttrValueId(), detailRequest.getProductId(), PublishConstants.PRODUCT_TYPE_SHOP);
                if (ObjectUtil.isNull(attrValue)) {
                    throw new ServiceException("商品规格信息不存在，请刷新后重新选择");
                }
                if (attrValue.getStock() < detailRequest.getProductNum()) {
                    throw new ServiceException("商品规格库存不足，请刷新后重新选择");
                }
//                SystemUserLevel userLevel = null;
//                if (user.getLevel() > 0) {
//                    userLevel = systemUserLevelService.getByLevelId(user.getLevel());
//                }
                OrderInfoDetailVo detailVo = new OrderInfoDetailVo();
                detailVo.setProductId(storeProduct.getId());
                detailVo.setProductName(storeProduct.getStoreName());
                detailVo.setAttrValueId(attrValue.getId());
                detailVo.setSku(attrValue.getSku());
                detailVo.setPrice(attrValue.getPrice());
                detailVo.setPayNum(detailRequest.getProductNum());
                detailVo.setImage(StrUtil.isNotBlank(attrValue.getImage()) ? attrValue.getImage() : storeProduct.getImage());
                detailVo.setVolume(attrValue.getVolume());
                detailVo.setWeight(attrValue.getWeight());
                detailVo.setTempId(storeProduct.getTempId());
                detailVo.setIsSub(storeProduct.getIsSub());
                detailVo.setProductType(PublishConstants.PRODUCT_TYPE_SHOP);
                detailVo.setVipPrice(detailVo.getPrice());
                detailVo.setGiveIntegral(storeProduct.getGiveIntegral());
//                if (ObjectUtil.isNotNull(userLevel)) {
//                    detailVo.setVipPrice(detailVo.getPrice());
//                }
                detailVoList.add(detailVo);
            }
        }
        // 再次购买
        if (PreOrderTypeEnum.AGAIN.getValue().equals(request.getPreOrderType())) {
            PreOrderDetailVo detailRequest = request.getOrderDetails().get(0);
            detailVoList = validatePreOrderAgain(detailRequest, userId);
        }
        // 填充订单详情
        orderInfoVo.setOrderDetailList(detailVoList);
        // 返回预下单信息
        return orderInfoVo;
    }

    /**
     * 填充购物车-预下单校验
     */
    private List<OrderInfoDetailVo> validatePreOrderShopping(PreOrderVo request, long userId) {
        List<OrderInfoDetailVo> detailVoList = CollUtil.newArrayList();
        // 获取用户会员等级福利
//        SystemUserLevel userLevel = null;
//        if (user.getLevel() > 0) {
//            userLevel = systemUserLevelService.getByLevelId(user.getLevel());
//        }
//        SystemUserLevel finalUserLevel = userLevel;
        request.getOrderDetails().forEach(e -> {
            Long cartId = e.getShoppingCartId();
            if (ObjectUtil.isNull(e.getShoppingCartId())) {
                throw new ServiceException("购物车编号不能为空");
            }

            PStoreCart storeCart = cartMapper.selectOne(new LambdaQueryWrapper<PStoreCart>().eq(PStoreCart::getId, cartId).eq(PStoreCart::getUid, userId));
            if (ObjectUtil.isNull(storeCart)) {
                throw new ServiceException("未找到对应的购物车信息");
            }
            // 查询商品信息
            PStoreProduct storeProduct = productMapper.selectById(storeCart.getProductId());
            if (ObjectUtil.isNull(storeProduct)) {
                throw new ServiceException("商品信息不存在，请刷新后重新选择");
            }

            if (PublishConstants.COMMON_NO.equals(storeProduct.getIsShow())) {
                throw new ServiceException("商品已下架！");
            }

            if (storeProduct.getStock() < storeCart.getCartNum()) {
                throw new ServiceException("商品库存不足，请刷新后重新选择");
            }
            // 查询商品规格属性值信息
            PStoreProductAttrValue attrValue = getByIdAndProductIdAndType(Long.parseLong(storeCart.getProductAttrUnique()), storeCart.getProductId(), PublishConstants.PRODUCT_TYPE_SHOP);
            if (ObjectUtil.isNull(attrValue)) {
                throw new ServiceException("商品规格信息不存在，请刷新后重新选择");
            }
            // 校验库存
            if (attrValue.getStock() < storeCart.getCartNum()) {
                throw new ServiceException("商品规格库存不足，请刷新后重新选择");
            }
            // 填充订单详情
            OrderInfoDetailVo detailVo = new OrderInfoDetailVo();
            detailVo.setProductId(storeProduct.getId());
            detailVo.setProductName(storeProduct.getStoreName());
            detailVo.setAttrValueId(attrValue.getId());
            detailVo.setSku(attrValue.getSku());
            detailVo.setPrice(attrValue.getPrice());
            detailVo.setPayNum(storeCart.getCartNum());
            detailVo.setImage(StrUtil.isNotBlank(attrValue.getImage()) ? attrValue.getImage() : storeProduct.getImage());
            detailVo.setVolume(attrValue.getVolume());
            detailVo.setWeight(attrValue.getWeight());
            detailVo.setTempId(storeProduct.getTempId());
            detailVo.setGiveIntegral(storeProduct.getGiveIntegral());
            detailVo.setIsSub(storeProduct.getIsSub());
            detailVo.setProductType(PublishConstants.PRODUCT_TYPE_SHOP);
            detailVo.setVipPrice(detailVo.getPrice());
            // 设置会员价格
//            if (ObjectUtil.isNotNull(finalUserLevel)) {
//                BigDecimal vipPrice = detailVo.getPrice().multiply(new BigDecimal(finalUserLevel.getDiscount())).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
//                detailVo.setVipPrice(vipPrice);
//            }
            detailVoList.add(detailVo);
        });

        return detailVoList;
    }

    /**
     * 秒杀-预下单校验
     */
    private OrderInfoDetailVo validatePreOrderSeckill(PreOrderDetailVo detailRequest, long userId) {
        long seckillId = detailRequest.getSeckillId();
        PStoreSeckill storeSeckill = seckillMapper.selectOne(new LambdaQueryWrapper<PStoreSeckill>().eq(PStoreSeckill::getId, seckillId).eq(PStoreSeckill::getIsShow, PublishConstants.COMMON_YES));
        if (storeSeckill.getStatus().equals(0)) {
            throw new ServiceException("秒杀商品已关闭");
        }

        PStoreProductAttrValue seckillAttrValue = getByIdAndProductIdAndType(detailRequest.getAttrValueId(), detailRequest.getProductId(), PublishConstants.PRODUCT_TYPE_SECKILL);
        if (ObjectUtil.isNull(seckillAttrValue)) {
            throw new ServiceException("秒杀商品规格不存在");
        }
        // 公共校验秒杀
        commonValidateSeckill(storeSeckill, seckillAttrValue, LoginHelper.getUserId(), detailRequest.getProductNum());
        // 填充订单-商品详情
        OrderInfoDetailVo detailVo = new OrderInfoDetailVo();
        detailVo.setProductId(storeSeckill.getProductId());
        detailVo.setProductName(storeSeckill.getTitle());
        detailVo.setAttrValueId(seckillAttrValue.getId());
        detailVo.setSku(seckillAttrValue.getSku());
        detailVo.setPrice(seckillAttrValue.getPrice());
        detailVo.setPayNum(detailRequest.getProductNum());
        detailVo.setImage(StrUtil.isNotBlank(seckillAttrValue.getImage()) ? seckillAttrValue.getImage() : storeSeckill.getImage());
        detailVo.setVolume(seckillAttrValue.getVolume());
        detailVo.setWeight(seckillAttrValue.getWeight());
        detailVo.setTempId(storeSeckill.getTempId());
        detailVo.setProductType(PublishConstants.PRODUCT_TYPE_SECKILL);

        return detailVo;
    }

    /**
     * 砍价预下单校验
     */
    private OrderInfoDetailVo validatePreOrderBargain(PreOrderDetailVo detailRequest, long userId) {
//        if (detailRequest.getBargainUserId() <= 0) {
//            throw new ServiceException("用户砍价活动id必须大于0");
//        }
//        // 砍价部分判断
//        Integer bargainId = detailRequest.getBargainId();
//        StoreBargain storeBargain = storeBargainService.getByIdException(bargainId);
//        StoreProductAttrValue bargainAttrValue = storeProductAttrValueService.getByIdAndProductIdAndType(detailRequest.getAttrValueId(), bargainId, Constants.PRODUCT_TYPE_BARGAIN);
//        if (ObjectUtil.isNull(bargainAttrValue)) {
//            throw new ServiceException("砍价商品规格不存在");
//        }
//        commonValidateBargain(storeBargain, bargainAttrValue, detailRequest.getBargainUserId(), user, detailRequest.getProductNum());
//
//
//        OrderInfoDetailVo detailVo = new OrderInfoDetailVo();
//        detailVo.setProductId(storeBargain.getProductId());
//        detailVo.setProductName(storeBargain.getTitle());
//        detailVo.setAttrValueId(bargainAttrValue.getId());
//        detailVo.setSku(bargainAttrValue.getSuk());
//        detailVo.setPrice(storeBargain.getMinPrice());
//        detailVo.setPayNum(detailRequest.getProductNum());
//        detailVo.setImage(StrUtil.isNotBlank(bargainAttrValue.getImage()) ? bargainAttrValue.getImage() : bargainAttrValue.getImage());
//        detailVo.setVolume(bargainAttrValue.getVolume());
//        detailVo.setWeight(bargainAttrValue.getWeight());
//        detailVo.setTempId(storeBargain.getTempId());
//        detailVo.setProductType(Constants.PRODUCT_TYPE_BARGAIN);
//        return detailVo;
        return null;
    }

    /**
     * 拼团预下单校验
     */
    private OrderInfoDetailVo validatePreOrderCombination(PreOrderDetailVo detailRequest, long userId) {
//        // 拼团部分判断
//        Integer combinationId = detailRequest.getCombinationId();
//        StoreCombination storeCombination = storeCombinationService.getByIdException(combinationId);
//        if (storeCombination.getStock().equals(0) || detailRequest.getProductNum() > storeCombination.getStock()) {
//            throw new ServiceException("拼团商品库存不足");
//        }
//        StoreProductAttrValue combinationAttrValue = storeProductAttrValueService.getByIdAndProductIdAndType(detailRequest.getAttrValueId(), combinationId, Constants.PRODUCT_TYPE_PINGTUAN);
//        if (ObjectUtil.isNull(combinationAttrValue)) {
//            throw new ServiceException("拼团商品规格不存在");
//        }
//        commonValidateCombination(storeCombination, combinationAttrValue, user, detailRequest.getProductNum());
//
//        OrderInfoDetailVo detailVo = new OrderInfoDetailVo();
//        detailVo.setProductId(storeCombination.getProductId());
//        detailVo.setProductName(storeCombination.getTitle());
//        detailVo.setAttrValueId(combinationAttrValue.getId());
//        detailVo.setSku(combinationAttrValue.getSuk());
//        detailVo.setPrice(combinationAttrValue.getPrice());
//        detailVo.setPayNum(detailRequest.getProductNum());
//        detailVo.setImage(StrUtil.isNotBlank(combinationAttrValue.getImage()) ? combinationAttrValue.getImage() : combinationAttrValue.getImage());
//        detailVo.setVolume(combinationAttrValue.getVolume());
//        detailVo.setWeight(combinationAttrValue.getWeight());
//        detailVo.setTempId(storeCombination.getTempId());
//        detailVo.setProductType(Constants.PRODUCT_TYPE_PINGTUAN);
//        return detailVo;
        return null;
    }

    /**
     * 公共校验秒杀
     */
    private Map<String, Object> commonValidateSeckill(PStoreSeckill storeSeckill, PStoreProductAttrValue seckillAttrValue, long userId, Integer productNum) {
        if (storeSeckill.getStock().equals(0) || productNum > storeSeckill.getStock()) {
            throw new ServiceException("秒杀商品库存不足");
        }

        if (seckillAttrValue.getStock() <= 0 || seckillAttrValue.getQuota() <= 0 || productNum > seckillAttrValue.getStock()) {
            throw new ServiceException("秒杀商品规格库存不足");
        }
        // 普通商品部分判断
        PStoreProduct product = productMapper.selectById(storeSeckill.getProductId());
        if (ObjectUtil.isNull(product)) {
            throw new ServiceException("秒杀主商品不存在");
        }
        if (product.getStock().equals(0) || productNum > product.getStock()) {
            throw new ServiceException("秒杀主商品库存不足");
        }
        // 主商品sku
        PStoreProductAttrValue productAttrValue = getByProductIdAndSkuAndType(storeSeckill.getProductId(), seckillAttrValue.getSku(), PublishConstants.PRODUCT_TYPE_SHOP);
        if (ObjectUtil.isNull(productAttrValue)) {
            throw new ServiceException("秒杀主商品规格不存在");
        }
        if (productAttrValue.getStock() <= 0 || productNum > productAttrValue.getStock()) {
            throw new ServiceException("秒杀主商品规格库存不足");
        }
        // 判断秒杀是否过期 1:日期是否在范围内 2：时间是否在每天的时间段内
        PStoreSeckillManger seckillManger = seckillMangerMapper.selectById(storeSeckill.getTimeId());
        if (ObjectUtil.isNull(seckillManger)) {
            throw new ServiceException("秒杀时段不存在");
        }
        // 判断日期是否过期
        DateTime nowDateTime = cn.hutool.core.date.DateUtil.date();
        String stopTimeStr = DateUtil.dateToStr(storeSeckill.getStopTime(), PublishConstants.DATE_FORMAT_DATE);
        Date stopDate = DateUtil.strToDate(stopTimeStr + " " + seckillManger.getEndTime() + ":00:00", PublishConstants.DATE_FORMAT);
        if (nowDateTime.getTime() - stopDate.getTime() >= 0) {
            throw new ServiceException("秒杀商品已过期");
        }
        // 判断是否在秒杀时段内（小时）,秒杀开始时间 <= 当前时间 <= 秒杀结束时间
        int hour = nowDateTime.getField(Calendar.HOUR_OF_DAY);// 现在的小时
        if (seckillManger.getStartTime() > hour || seckillManger.getEndTime() < hour) {
            throw new ServiceException("秒杀商品已过期");
        }

        // 判断秒杀购买次数
        // 当天参与活动次数 -根据用户和秒杀信息查询当天订单判断订单数量
        List<PStoreOrder> userCurrentDaySecKillOrders = getUserCurrentDaySecKillOrders(userId, storeSeckill.getId());
        if (CollUtil.isNotEmpty(userCurrentDaySecKillOrders)) {
            // 判断是否有待支付订单
            List<PStoreOrder> unPayOrders = userCurrentDaySecKillOrders.stream().filter(e -> StringUtils.isNotBlank(e.getPaid())).collect(Collectors.toList());
            if (unPayOrders.size() > 0) {
                throw new ServiceException("您有秒杀待支付订单，请支付后再购买");
            }

            // 判断是否达到上限
            if (userCurrentDaySecKillOrders.size() >= storeSeckill.getNum()) {
                throw new ServiceException("您已经达到当前秒杀活动上限");
            }
        }

        Map<String, Object> record = new HashMap<>();
        record.put("productAttrValue", productAttrValue);
        return record;
    }

    /**
     * 根据sku查询
     * @param productId 商品id
     * @param sku   sku
     * @param type  规格类型
     * @return StoreProductAttrValue
     */
    private PStoreProductAttrValue getByProductIdAndSkuAndType(long productId, String sku, String type) {
        LambdaQueryWrapper<PStoreProductAttrValue> lqw = Wrappers.lambdaQuery();
        lqw.eq(PStoreProductAttrValue::getProductId, productId);
        lqw.eq(PStoreProductAttrValue::getSku, sku);
        lqw.eq(PStoreProductAttrValue::getType, type);
        return attrValueMapper.selectOne(lqw);
    }

    /**
     * 获取用户当天的秒杀数量
     *
     * @param userId       用户uid
     * @param seckillId 秒杀商品id
     * @return 用户当天的秒杀商品订单数量
     */
    private List<PStoreOrder> getUserCurrentDaySecKillOrders(long userId, long seckillId) {
        String dayStart = DateUtil.nowDateTime(PublishConstants.DATE_FORMAT_START);
        String dayEnd = DateUtil.nowDateTime(PublishConstants.DATE_FORMAT_END);
        LambdaQueryWrapper<PStoreOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(PStoreOrder::getUid, userId);
        lqw.eq(PStoreOrder::getSeckillId, seckillId);
        lqw.between(PStoreOrder::getCreateTime, dayStart, dayEnd);
        return baseMapper.selectList(lqw);
    }

    /**
     * 根据sku查询
     *
     * @param productId 商品id
     * @param type      规格类型
     * @return StoreProductAttrValue
     */
    private PStoreProductAttrValue getByIdAndProductIdAndType(long id, long productId, String type) {
        LambdaQueryWrapper<PStoreProductAttrValue> lqw = Wrappers.lambdaQuery();
        lqw.eq(PStoreProductAttrValue::getId, id);
        lqw.eq(PStoreProductAttrValue::getProductId, productId);
        lqw.eq(PStoreProductAttrValue::getType, type);
        return attrValueMapper.selectLeftOssOne(lqw);
    }

    /**
     * 再次下单预下单校验
     *
     * @param detailRequest 请求参数
     * @return List<OrderInfoDetailVo>
     */
    private List<OrderInfoDetailVo> validatePreOrderAgain(PreOrderDetailVo detailRequest, long userId) {
        List<OrderInfoDetailVo> detailVoList = CollUtil.newArrayList();
        if (StrUtil.isBlank(detailRequest.getOrderNo())) {
            throw new ServiceException("再次购买订单编号不能为空");
        }
        PStoreOrder storeOrder = getByOrderIdException(detailRequest.getOrderNo());
        if (Integer.parseInt(storeOrder.getRefundStatus()) > 0 || !storeOrder.getStatus().equals(ShopStatus.FINISH.getValue())) {
            throw new ServiceException("只有已完成状态订单才能再次购买");
        }
        if (storeOrder.getSeckillId() > 0 || storeOrder.getBargainId() > 0 || storeOrder.getCombinationId() > 0) {
            throw new ServiceException("活动商品订单不能再次购买");
        }
        // 获取订单详情
        List<StoreOrderInfoOldVo> infoVoList = getVoListByOrderId(storeOrder.getId());
        if (CollUtil.isEmpty(infoVoList)) {
            throw new ServiceException("订单详情未找到");
        }
//        SystemUserLevel userLevel = null;
//        if (user.getLevel() > 0) {
//            userLevel = systemUserLevelService.getByLevelId(user.getLevel());
//        }
//        SystemUserLevel finalUserLevel = userLevel;
        infoVoList.forEach(e -> {
            OrderInfoDetailVo detailVo = e.getInfo();
            // 查询商品信息
            PStoreProduct storeProduct = productMapper.selectById(detailVo.getProductId());
            if (ObjectUtil.isNull(storeProduct)) {
                throw new ServiceException("商品信息不存在，请刷新后重新选择");
            }
            if (PublishConstants.COMMON_NO.equals(storeProduct.getIsShow())) {
                throw new ServiceException("商品已下架，请刷新后重新选择");
            }
            if (storeProduct.getStock() < detailVo.getPayNum()) {
                throw new ServiceException("商品库存不足，请刷新后重新选择");
            }
            // 查询商品规格属性值信息
            PStoreProductAttrValue attrValue = getByIdAndProductIdAndType(detailVo.getAttrValueId(), detailVo.getProductId(), PublishConstants.PRODUCT_TYPE_SHOP);
            if (ObjectUtil.isNull(attrValue)) {
                throw new ServiceException("商品规格信息不存在，请刷新后重新选择");
            }
            if (attrValue.getStock() < detailVo.getPayNum()) {
                throw new ServiceException("商品规格库存不足，请刷新后重新选择");
            }
            OrderInfoDetailVo tempDetailVo = new OrderInfoDetailVo();
            tempDetailVo.setProductId(storeProduct.getId());
            tempDetailVo.setProductName(storeProduct.getStoreName());
            tempDetailVo.setAttrValueId(attrValue.getId());
            tempDetailVo.setSku(attrValue.getSku());
            tempDetailVo.setPrice(attrValue.getPrice());
            tempDetailVo.setPayNum(detailVo.getPayNum());
            tempDetailVo.setImage(StrUtil.isNotBlank(attrValue.getImage()) ? attrValue.getImage() : storeProduct.getImage());
            tempDetailVo.setVolume(attrValue.getVolume());
            tempDetailVo.setWeight(attrValue.getWeight());
            tempDetailVo.setTempId(storeProduct.getTempId());
            tempDetailVo.setGiveIntegral(storeProduct.getGiveIntegral());
            tempDetailVo.setIsSub(storeProduct.getIsSub());
            tempDetailVo.setProductType(PublishConstants.PRODUCT_TYPE_SHOP);
            tempDetailVo.setVipPrice(attrValue.getPrice());
//            if (ObjectUtil.isNotNull(finalUserLevel)) {
//                tempDetailVo.setVipPrice(attrValue.getPrice());
//            }
            detailVoList.add(tempDetailVo);
        });
        return detailVoList;
    }

    /**
     * 根据id集合查询数据，返回 map
     *
     * @param orderId 订单id
     * @return HashMap<Integer, StoreCart>
     */
    public List<StoreOrderInfoOldVo> getVoListByOrderId(long orderId) {
        LambdaQueryWrapper<PStoreOrderInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PStoreOrderInfo::getOrderId, orderId);
        List<PStoreOrderInfo> systemStoreStaffList = orderInfoMapper.selectList(lambdaQueryWrapper);
        if (systemStoreStaffList.size() < 1) {
            return null;
        }

        List<StoreOrderInfoOldVo> storeOrderInfoVoList = new ArrayList<>();
        for (PStoreOrderInfo storeOrderInfo : systemStoreStaffList) {
            //解析商品详情JSON
            StoreOrderInfoOldVo storeOrderInfoVo = new StoreOrderInfoOldVo();
            BeanUtils.copyProperties(storeOrderInfo, storeOrderInfoVo, "info");
            storeOrderInfoVo.setInfo(JsonUtils.parseObject(storeOrderInfo.getInfo(), OrderInfoDetailVo.class));
            storeOrderInfoVoList.add(storeOrderInfoVo);
        }
        return storeOrderInfoVoList;
    }

    /**
     * 校验订单
     *
     * @param orderId
     * @return
     */
    private PStoreOrder getByOrderIdException(String orderId) {
        PStoreOrder storeOrder = baseMapper.selectById(orderId);
        if (ObjectUtil.isNull(storeOrder)) {
            throw new ServiceException("订单不存在");
        }

        return storeOrder;
    }

    @Override
    public TableDataInfo<PStoreOrder> integralRecordList(PageQuery pageQuery) {
        pageQuery.setPageNum((pageQuery.getPageNum() - 1) * pageQuery.getPageSize());
        return TableDataInfo.build(this.baseMapper.integralRecordList(LoginHelper.getUserId(), pageQuery));
    }

    @Override
    public void insertOrderByBo(POrderBo bo) {
        List<PStoreOrder> orders = new ArrayList<>();
        PUserAddress address = bo.getAddress();
        String addressDetail = address.getProvince() + " " + address.getCity() + " " + address.getDistrict() + " " + address.getDetail();
        for(PStoreCart product: bo.getProducts()) {
            PStoreOrder order = new PStoreOrder();
            order.setOrderId(bo.getOrderNo())
                .setUid(LoginHelper.getUserId())
                .setStatus(ShopStatus.UN_PAY.getValue())
                .setRealName(address.getRealName())
                .setUserPhone(address.getPhone())
                .setUserAddress(addressDetail)
                .setPayType(bo.getPayType())
                .setCombinationId(product.getProductId())
                .setTotalNum(product.getCartNum());
            if ("1".equals(product.getType())) {
                order.setUseIntegral(Integer.valueOf(product.getPrice().multiply(BigDecimal.valueOf(10)).multiply(new BigDecimal(product.getCartNum())).stripTrailingZeros().toPlainString()))
                    .setPayPrice(BigDecimal.valueOf(0))
                    .setPayPostage(BigDecimal.valueOf(0));
            } else {
                order.setPayPrice(product.getPrice().multiply(new BigDecimal(product.getCartNum())))
                    .setPayPostage(product.getPostage().multiply(new BigDecimal(product.getCartNum())));
            }

            orders.add(order);
        }
        if (this.baseMapper.insertBatch(orders)) {
            for(PStoreOrder order: orders) {
                PStoreProduct product = this.productMapper.selectOne(new LambdaQueryWrapper<PStoreProduct>().eq(PStoreProduct::getId, order.getCombinationId()));
                this.productMapper.update(null, new LambdaUpdateWrapper<PStoreProduct>()
                    .set(PStoreProduct::getSales, product.getSales() + order.getTotalNum())
                    /*.set(PStoreProduct::getStock, product.getStock() - order.getTotalNum())*/
                    .eq(PStoreProduct::getId, order.getCombinationId()));
            }
            cartMapper.delete(new LambdaQueryWrapper<PStoreCart>().in(PStoreCart::getId, bo.getProducts().stream().map(PStoreCart::getId).collect(Collectors.toList())));
        }
        /*Long couponId = bo.getCouponId();
        if (ObjectUtil.isNotEmpty(couponId)) {
            PAskCoupon coupon = askCouponMapper.selectById(couponId);
            if (ObjectUtil.isEmpty(coupon)) {
                //throw new ServiceException("非法购物券！");
            }
        }*/
    }

    @Override
    public List<PStoreOrder> orderDetail(String orderId) {
        return this.baseMapper.selectList(new LambdaQueryWrapper<PStoreOrder>().eq(PStoreOrder::getOrderId, orderId));
    }

    @Override
    public void askPayOk(List<PStoreOrder> orders) {
        if (orders.size() > 0) {
            String orderId = orders.get(0).getOrderId();
            this.baseMapper.update(null, new LambdaUpdateWrapper<PStoreOrder>().set(PStoreOrder::getPayTime, new Date())
                .set(PStoreOrder::getStatus, ShopStatus.UN_SHIPPING.getValue()).in(PStoreOrder::getOrderId, orderId));

            SysUser sysUser = userMapper.selectById(orders.get(0).getUid());
            BigDecimal actualPrice = new BigDecimal(0);
            for(PStoreOrder order: orders) {
                actualPrice = actualPrice.add(order.getPayPrice());
            }
            this.pOrderService.setTheCommission(sysUser, actualPrice, Long.parseLong(orderId));
        }
    }

    @Override
    public List<PStoreOrder> shopOrderDetail(String orderId) {
        return this.baseMapper.shopOrderDetail(orderId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void blanceShop(POrderBo bo) {
        //  判断用户余额是否超过购买的商品总价钱
        SysUser user = this.userMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserId, LoginHelper.getUserId()));

        /*BigDecimal actualPrice = new BigDecimal(0);
        for(PStoreCart cart: bo.getProducts()) {
            actualPrice = actualPrice.add(cart.getPrice().multiply(new BigDecimal(cart.getCartNum())));
            actualPrice = actualPrice.add(cart.getPostage().multiply(new BigDecimal(cart.getCartNum())));
        }*/
        if (user.getBalance().compareTo(bo.getActualPrice()) == -1) {
            throw new ServiceException("余额不足！");
        }
        // 扣除用户余额
        this.userMapper.update(null, new LambdaUpdateWrapper<SysUser>().set(SysUser::getBalance, user.getBalance().subtract(bo.getActualPrice())).eq(SysUser::getUserId, user.getUserId()));

        // 创建订单 修改状态 分销
        if (StringUtils.isEmpty(bo.getOrderNo())) {
            bo.setOrderNo(CharUtil.getRandomNum(16));
            this.insertOrderByBo(bo);
        }
        List<PStoreOrder> orders = this.orderDetail(bo.getOrderNo());
        this.askPayOk(orders);
        // 添加账单记录
        PUserBill bill = new PUserBill();
        bill.setOrderNo(bo.getOrderNo())
            .setUserId(LoginHelper.getUserId())
            .setCategory("2")
            .setPayType("0")
            .setType("0")
            .setNumber(bo.getActualPrice());
        this.pUserBillMapper.insert(bill);
    }

    @Override
    public void integralShop(POrderBo bo) {
        //  判断用户积分是否购买
        SysUser user = this.userMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserId, LoginHelper.getUserId()));

        BigDecimal actualPrice = new BigDecimal(0);
        for(PStoreCart cart: bo.getProducts()) {
            actualPrice = actualPrice.add(cart.getPrice().multiply(BigDecimal.valueOf(10)).multiply(new BigDecimal(cart.getCartNum())));
        }
        if (new BigDecimal(user.getIntegral()).compareTo(actualPrice) == -1) {
            throw new ServiceException("积分不足！");
        }

        // 扣除用户余额
        this.userMapper.update(null, new LambdaUpdateWrapper<SysUser>().set(SysUser::getIntegral, user.getIntegral() - Integer.parseInt(actualPrice.stripTrailingZeros().toPlainString())).eq(SysUser::getUserId, user.getUserId()));

        // 创建订单 修改状态 分销
        this.insertOrderByBo(bo);
        List<PStoreOrder> orders = this.orderDetail(bo.getOrderNo());
        this.askPayOk(orders);
        // 添加账单记录
        PUserBill bill = new PUserBill();
        bill.setOrderNo(bo.getOrderNo())
            .setUserId(LoginHelper.getUserId())
            .setCategory("1")
            .setType("0")
            .setNumber(actualPrice);
        this.pUserBillMapper.insert(bill);
    }

    @Override
    public Map<String, Object> shopPersonCenter() {
        Map<String, Object> map = new HashMap<>();
        SysUser user = this.userMapper.selectPersonCenter(LoginHelper.getUserId());
        map.put("balance", user.getBalance());
        map.put("distributionIncome", user.getDistributionIncome());
        map.put("integral", user.getIntegral());
        map.put("toPayCount", user.getToPayCount());
        map.put("unShipping", user.getUnShipping());
        map.put("unGetting", user.getUnGetting());
        map.put("getting", user.getGetting());
        map.put("finish", user.getFinish());
        return map;
    }

    @Override
    public List<PStoreOrder> shopOrderList(String ind, PageQuery pageQuery) {
        pageQuery.setPageNum((pageQuery.getPageNum() - 1) * pageQuery.getPageSize());
        return this.baseMapper.shopOrderList(ind, LoginHelper.getUserId(), pageQuery);
    }

    @Override
    public void refundApply(PStoreOrder storeOrder) {
        this.baseMapper.update(null, new LambdaUpdateWrapper<PStoreOrder>()
            .set(PStoreOrder::getRefundReasonWap, storeOrder.getRefundReasonWap())
            .set(PStoreOrder::getRefundReasonWapExplain, storeOrder.getRefundReasonWapExplain())
            .set(!StringUtils.isEmpty(storeOrder.getRefundReasonWapImg()), PStoreOrder::getRefundReasonWapImg, storeOrder.getRefundReasonWapImg())
            .set(ObjectUtils.isNotEmpty(storeOrder.getRefundPrice()), PStoreOrder::getRefundPrice, storeOrder.getRefundPrice())
            .set(PStoreOrder::getStatus, ShopStatus.APPLY_REFUND.getValue())
            .eq(PStoreOrder::getId, storeOrder.getId()));
    }
}
